/*
 *Copyright 2021-2023 NERCIS
 *
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
 */

package cn.ac.nercis.pes.service.project.imported;

import cn.ac.nercis.pes.common.constant.evaluation.SecurityThreatMode;
import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.project.ImportConflictDTO;
import cn.ac.nercis.pes.model.standard.prepare.SecurityThreatSDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.SecurityThreatRepository;
import cn.ac.nercis.pes.repository.model.evaluation.SecurityThreatDO;
import cn.ac.nercis.pes.service.utils.CheckFieldUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 安全威胁信息导入服务
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class SecurityThreatImportService {
    private final SecurityThreatRepository securityThreatRepository;

    @Autowired
    public SecurityThreatImportService(SecurityThreatRepository securityThreatRepository) {
        this.securityThreatRepository = securityThreatRepository;
    }

    public Result<List<ImportConflictDTO>> checkSecurityThreat(@NonNull String systemId, List<SecurityThreatSDTO> securityThreats) {
        List<SecurityThreatDO> sourceData = this.securityThreatRepository.findAllBySystemId(systemId);
        if (CollectionUtils.isEmpty(sourceData)) {
            return Result.success();
        }
        List<ImportConflictDTO> conflictData = securityThreats.stream()
                .flatMap(ec -> this.checkSecurityThreat(ec, sourceData).stream())
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return Result.success(conflictData);
    }

    public Result<String> importSecurityThreat(@NonNull String systemId, List<SecurityThreatSDTO> securityThreats, Boolean cover) {
        List<SecurityThreatDO> sourceData = this.securityThreatRepository.findAllBySystemId(systemId);
        Result<String> result = Result.success();
        for (SecurityThreatSDTO item : securityThreats) {
            result = this.importSecurityThreat(systemId, item, sourceData, cover);
            if (!result.isSuccess()) {
                break;
            }
        }
        return result;
    }

    private List<ImportConflictDTO> checkSecurityThreat(@NonNull SecurityThreatSDTO importData, List<SecurityThreatDO> sourceData) {
        SecurityThreatDO entity = sourceData.stream()
                .filter(st -> StringUtils.equals(st.getCode(), importData.getCode()))
                .findFirst().orElse(null);
        if (Objects.isNull(entity)) {
            return Collections.emptyList();
        }
        return CheckFieldUtils.checkField(entity, importData);
    }

    private Result<String> importSecurityThreat(String systemId, @NonNull SecurityThreatSDTO importData, List<SecurityThreatDO> sourceData, Boolean cover) {
        SecurityThreatDO entity = sourceData.stream()
                .filter(st -> StringUtils.equals(st.getCode(), importData.getCode()))
                .findFirst().orElse(null);
        if (Objects.isNull(entity)) {
            return createSecurityThreat(systemId, importData);
        } else {
            return modifySecurityThreat(entity, importData, cover);
        }
    }

    private Result<String> createSecurityThreat(String systemId, SecurityThreatSDTO importData) {
        if(Objects.isNull(importData.getMode())){
            importData.setMode(SecurityThreatMode.KNOWLEDGE);
        }
        SecurityThreatDO entity = SecurityThreatDO.builder()
                .systemId(systemId)
                .threadId(importData.getThreadId())
                .type(importData.getType())
                .code(importData.getCode())
                .name(importData.getName())
                .sort(importData.getSort())
                .mode(importData.getMode())
                .build();
        entity.setCreateTime(LocalDateTime.now());
        return Optional.of(entity)
                .map(this.securityThreatRepository::save)
                .map(SecurityThreatDO::getId)
                .map(Result::success)
                .orElse(Result.failed(String.format("导入%s安全威胁信息，创建失败", importData.getName())));
    }

    private Result<String> modifySecurityThreat(SecurityThreatDO sourceData, SecurityThreatSDTO importData, Boolean cover) {
        if(Objects.isNull(importData.getMode())){
            importData.setMode(SecurityThreatMode.KNOWLEDGE);
        }
        sourceData.setThreadId(CheckFieldUtils.applyContent(sourceData.getThreadId(), importData.getThreadId(), cover));
        sourceData.setType(CheckFieldUtils.applyContent(sourceData.getType(), importData.getType(), cover));
        sourceData.setName(CheckFieldUtils.applyContent(sourceData.getName(), importData.getName(), cover));
        sourceData.setSort(CheckFieldUtils.applyContent(sourceData.getSort(), importData.getSort(), cover));
        sourceData.setMode(CheckFieldUtils.applyContent(sourceData.getMode(),importData.getMode(),cover));
        sourceData.setModifyTime(LocalDateTime.now());
        return Optional.of(sourceData)
                .map(this.securityThreatRepository::save)
                .map(SecurityThreatDO::getId)
                .map(Result::success)
                .orElse(Result.failed(String.format("导入%s安全威胁信息，修改失败", importData.getName())));
    }
}
